package segmentTree;

import java.util.Arrays;

/**
 * 
 * @Title: SegmentTree.java 
 * @Package binaryTree.segmentTree 
 * @Description: 线段树
 * @author CandyWall   
 * @date 2021年1月9日 下午9:02:46 
 * @version V1.0
 */
public class SegmentTree<E> {
    private E[] data;
    private E[] tree;
    // 线段树父节点如何融合左右孩子节点的值
    public interface Merger<E> {
        E merge(E a, E b);
    }
    
    private Merger<E> merger;
    
    public void setMerger(Merger merger) {
        this.merger = merger;
    }
    
    public SegmentTree(E[] arr, Merger merger) {
        this.merger = merger;
        data = Arrays.copyOf(arr, arr.length);
        /*data = (E[]) new Object[arr.length];
        for(int i = 0; i < arr.length; i++) {
            data[i] = arr[i];
        }*/
        
        tree = (E[]) new Object[4 * arr.length];
        buildSegmentTree(0, 0, data.length - 1);
    }
    
    public SegmentTree(E[] arr) {
        this(arr, null);
    }
    
    // 在treeIndex的位置创建表示区间[l...r]的线段树
    private void buildSegmentTree(int treeIndex, int l, int r) {
        if(l == r) {
            tree[treeIndex] = data[l];
            return;
        }
        
        int leftTreeIndex = getLeftChildIndex(treeIndex);
        int rightTreeIndex = getRightChildIndex(treeIndex);
        
        //int mid = l + (r - l) / 2;
        int mid = l + ((r - l) >> 1);
        buildSegmentTree(leftTreeIndex, l, mid);
        buildSegmentTree(rightTreeIndex, mid + 1, r);
        
        // tree[treeIndex] = tree[leftTreeIndex] + tree[rightTreeIndex];
        if(merger != null) {
            tree[treeIndex] = merger.merge(tree[leftTreeIndex], tree[rightTreeIndex]);
        }
    }

    /**
     * 校验待操作的数组下标是否合法
     */
    private void checkArrayIndexRange(int index) {
        if(index >= data.length || index < 0) {
            throw new IllegalArgumentException("索引index不合法！");
        }
    }
    
    public E get(int index) {
        checkArrayIndexRange(index);
        return data[index];
    }
    
    public int getSize() {
        return data.length;
    }
    
    // 在完全二叉树表示中，根据父节点的索引，获取左孩子节点的索引
    private int getLeftChildIndex(int parentIndex) {
        return parentIndex * 2 + 1;
    }
    
    // 在完全二叉树表示中，根据父节点的索引，获取右孩子节点的索引
    private int getRightChildIndex(int parentIndex) {
        return parentIndex * 2 + 2;
    }
    
    // 返回区间[l, r]的值
    public E query(int queryL, int queryR) {
        checkArrayIndexRange(queryL);
        checkArrayIndexRange(queryR);
        if(queryL > queryR) {
            throw new IllegalArgumentException("索引index不合法！");
        }
        return query(0, 0, data.length - 1, queryL, queryR);
    }
    
    // 在treeIndex为根的线段树[l...r]的范围里，搜索区间[queryL...queryR]的值
    private E query(int treeIndex, int l, int r, int queryL, int queryR) {
        if(l == queryL && r == queryR) {
            return tree[treeIndex];
        }
        
        int mid = l + ((r - l) >> 1);
        int leftChildIndex = getLeftChildIndex(treeIndex);
        int rightChildIndex = getRightChildIndex(treeIndex);
        if(queryR <= mid) {
            return query(leftChildIndex, l, mid, queryL, queryR);
        }
        else if(queryL >= mid + 1) {
            return query(rightChildIndex, mid + 1, r, queryL, queryR);
        }
        
        E leftResult = query(leftChildIndex, l, mid, queryL, mid);
        E rightResult = query(rightChildIndex, mid + 1, r, mid + 1, queryR);
        return merger.merge(leftResult, rightResult);
    }
    
    // 将索引为index处的值修改为e
    public void set(int index, E e) {
        data[index] = e;
        set(0, 0, data.length - 1, index, e);
    }
    
    // 在treeIndex为根的线段树中[l...r]的范围里，更新index处的节点值为e
    private void set(int treeIndex, int l, int r, int index, E e) {
        if(l == r) {
            tree[treeIndex] = e;
            return;
        }
        int mid = l + ((r - l) >> 1);
        int leftChildIndex = getLeftChildIndex(treeIndex);
        int rightChildIndex = getRightChildIndex(treeIndex);
        if(index <= mid) {
            set(leftChildIndex, l, mid, index, e);
        } else { // (index > mid + 1) 
            set(rightChildIndex, mid + 1, r, index, e);
        }
        tree[treeIndex] = merger.merge(tree[leftChildIndex], tree[rightChildIndex]);
    }
    
    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for(int i = 0; ; i++) {
            if(tree[i] != null) {
                sb.append(tree[i]);
            } else {
                sb.append("null");
            }
            if(i == tree.length - 1) 
                return sb.append("]").toString();
            sb.append(", ");
        }
    }

    public static void main(String[] args) {
        Integer[] nums = {-2, 0, 3, -5, 2, -1};
        SegmentTree<Integer> segmentTree = new SegmentTree<>(nums, new Merger<Integer>() {
            @Override
            public Integer merge(Integer a, Integer b) {
                return a + b;
            }
        });
        System.out.println(segmentTree);
        System.out.println("[0, 2] = " + segmentTree.query(0, 2));
        System.out.println("[2, 5] = " + segmentTree.query(2, 5));
        System.out.println("[0, 5] = " + segmentTree.query(0, 5));
    }
}
